<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-03-22
 * Time: 11:35:00
 * Info: 应用中心
 */

namespace app\admin\controller;

use app\common\model\App as AppModel;
use think\addons\AddonsException;
use think\addons\Cloud;
use think\facade\Db;
use think\facade\View;
use think\facade\Cache;

class Appcenter extends Base
{

    /**
     * 初始化
     */
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 本地列表
     * @return \think\response\Json|void
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $type = $this->request->param('type');
            // 获取安装信息
            $model = AppModel::where(['type' => $type]);
            if ($type == 'template') {
                $module = $this->request->param('module');
                $model  = $model->where(['module' => $module]);
            }
            $data = $model->order('create_time', 'desc')->select()->toArray();

            // 查出未安装的插件。
            app()->cache->clear();
            $all = get_addons_info_all($type);
            if ( ! empty($all)) {
                if ( ! empty($module)) {
                    $all = $all[$module];
                }
                $newData = [];
                foreach ($all as $key => $value) {
                    $bl = true;
                    foreach ($data as $k => &$v) {
                        if ($key == $v['name']) {
                            $bl           = false;
                            $v['website'] = $value['website'] ?? '';
                            break;
                        }
                    }
                    if ($bl) {
                        $value['db_install'] = false;
                        $newData[]           = $value;
                    }
                }
                $data = array_merge($newData, $data);
            }
            if ( ! empty($data)) {
                // 根据本地的插件获取线上插件的信息
                $nameArr = [];
                foreach ($data as $key => $value) {
                    if ( ! isset($value['name'])) {
                        continue;
                    }
                    if ($value['name'] != 'default') {
                        $nameArr[] = $value['name'];
                    }
                    // 获取模板预览图
                    if (empty($value['image']) && $value['type'] == 'template') {

                    } else {
                        if (empty($value['image'])) {
                            $data[$key]['image'] = '/static/admin/images/nopic.png';
                        }
                    }
                    if (empty($data[$key]['config'])) {
                        // 获取配置
                        $data[$key]['config'] = get_addons_config($type, $value['name'], $value['module'] ?? '');
                    }
                }
            } else {
                $data = $all;
            }
            $count = count($data);
            $this->success('ok', $data, $count);
        }

        return View::fetch();
    }

    /**
     * 安装本地插件
     */
    public function installDb()
    {
        app()->cache->clear();
        $name   = $this->request->param('name');
        $type   = $this->request->param('type');
        $module = $this->request->param('module');
        if (empty($name)) {
            $this->error('参数name不能为空');
        }
        if ( ! preg_match("/^[a-zA-Z][a-zA-Z0-9_]*$/", $name)) {
            $this->error('插件名称只能是字母、数字、下划线');
        }
        if (empty($type)) {
            $this->error('类型不能为空');
        }
        if ($type == 'template' && empty($module)) {
            $this->error("模板模型不能为空");
        }
        // 获取信息
        $info = get_addons_info($name);
        if (empty($info)) {
            $this->error('info.ini文件的内容格式不正确');
        }

        // 检查是否已经安装
        $one = AppModel::where(['name' => $name])->find();
        if ( ! empty($one)) {
            $this->error('插件'.$name.'已经安装');
        }
        // 安装确认页
        if ($this->request->isPost()) {
            // 录入数据库
            $info['status'] = 1;
            $info['type']   = $type;

            $demodata = $this->request->param('demodata', '', 'intval');
            $force    = $this->request->param('force', 0);
            Db::startTrans();
            try {
                (new AppModel)->addInstall($info);
                if ($type != 'template') {
                    //插件安装
                    $obj = get_addons_instance($name);
                    if ( ! empty($obj)) {
                        // 调用插件安装
                        if (isset($obj->menu)) {
                            // 自动导入菜单
                            create_menu($obj->menu, $info['name']);
                        }
                        $obj->install();
                    }
                    Cloud::getInstance()->importSql($name);
                    Cloud::getInstance()->enable($name, $force == 1);
                    $demodataFile = app()->addons->getAddonsPath().$name.DIRECTORY_SEPARATOR.'demodata.sql';
                } else {
                    //模板安装

                }
                if ($demodata == 1) {
                    // 导入演示数据
                    if (is_file($demodataFile)) {
                        create_sql($demodataFile);
                    }
                }
                Db::commit();
            } catch (AddonsException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        app()->cache->clear();
        $this->success("插件安装成功");
    }

    /**
     * 在线启用禁用
     * @throws \think\addons\AddonsException
     */
    public function enable()
    {
        if ($this->request->isAjax()) {
            $name  = $this->request->param('name');
            $value = $this->request->param('val');
            if (empty($name)) {
                $this->error("参数".$name."不能为空");
            }
            if ( ! preg_match("/^[a-zA-Z][a-zA-Z0-9_]*$/", $name)) {
                $this->error('插件名称只能是字母、数字、下划线');
            }

            $addonInfo = AppModel::where(['name' => $name])->find();
            if (empty($addonInfo)) {
                $this->error("插件".$addonInfo['name']."没有安装");
            }

            if ($value == 1) { // 启用
                Cloud::getInstance()->enable($name);
                AppModel::where(['name' => $name])->save(['status' => 1]);
                status_menu(1, $name); // 启用菜单
                $this->app->cache->tag('addons')->clear();
                Cache::delete('hooks');
            } else { // 禁用
                Cloud::getInstance()->disable($name);
                AppModel::where(['name' => $name])->save(['status' => -1]);
                status_menu(0, $name); // 禁用菜单
                $this->app->cache->tag('addons')->clear();
                Cache::delete('hooks');
            }

            $this->success("修改成功");
        }
        $this->error('参数错误');
    }

    /**
     * 在线/本地卸载
     */
    public function uninstall()
    {
        if ($this->request->isAjax()) {
            $name   = $this->request->param('name', '');
            $type   = $this->request->param('type', '');
            $module = $this->request->param('module', '');

            if ( ! preg_match("/^[a-zA-Z][a-zA-Z0-9_]*$/", $name)) {
                $this->error('插件名称只能是字母、数字、下划线');
            }
            if (empty($name) || ($type != 'template' && $type != 'addon' && $type != 'module') || ($type == 'template' && empty($module))) {
                $this->error("参数不能为空");
            }

            // 获取已安装的插件信息
            $addonInfo = AppModel::where(['type' => $type, 'name' => $name])->find();
            if (empty($addonInfo)) {
                $this->error("插件".$name."没有安装");
            }

            if ('template' == $type) {
                // 卸载模板的情况，检测是否已经设置为主题了

            } else {
                if ($addonInfo['status'] == 1) {
                    $this->error("请先禁用后再操作~");
                }
            }

            Cloud::getInstance()->uninstall(['name' => $name, 'type' => $type, 'module' => $module]);
            if ($type != 'template') {
                // 删除菜单
                del_menu($name);
            }
            AppModel::where(['name' => $name])->delete();
            $this->app->cache->tag('addons')->clear();
            Cache::delete('hooks');
            $this->success("卸载成功");
        }
        $this->error("参数错误");
    }

    /**
     * 插件配置
     * @return string|void
     */
    public function setConfig()
    {
        $this->error('别偷懒，赶紧去开发');
    }
}
